<template>
  <div class="fabric-canvas-wrap">
    <canvas id="fabric-canvas" ref="fabric-canvas"></canvas>
  </div>
</template>

<script setup>
import { ref, useTemplateRef, onMounted, markRaw } from 'vue'
import * as fabric from 'fabric'
import { useFabricStore } from '@/stores/fabric'
import { storeToRefs } from 'pinia'
import {
  setInteractiveObjectControls,
  setGroupControls,
  setTextBoxControls,
  setLineControls,
  setRectControls,
} from '@/utils/customizedFabricControls'

const backgroundColor = import.meta.env.VITE_CANVAS_BACKGROUND_COLOR
const fabricStore = useFabricStore()
const { setCanvas } = fabricStore
const { boardWidth, boardHeight, canvas } = storeToRefs(fabricStore)

const canvasRef = useTemplateRef('fabric-canvas')

const boardstrokeWidth = Number(import.meta.env.VITE_CANVAS_DRAWBOARD_STROKEWIDTH)

const backgroundImage = new fabric.Rect({
  left: -boardstrokeWidth,
  top: -boardstrokeWidth,
  fill: 'transparent',
  stroke: '#07275b',
  strokeWidth: boardstrokeWidth,
  width: boardWidth.value + 2 * boardstrokeWidth,
  height: boardHeight.value + 2 * boardstrokeWidth,
  excludeFromExport: true,
})

const setDefaultOptions = () => {
  // 配置定位参考点位置
  fabric.BaseFabricObject.ownDefaults = {
    ...fabric.BaseFabricObject.ownDefaults,
    originX: 'center',
    originY: 'center',
  }
  // 全局配置对象上的控制点样式
  fabric.InteractiveFabricObject.ownDefaults = {
    ...fabric.InteractiveFabricObject.ownDefaults,
    transparentCorners: false,
    cornerColor: 'lightblue',
    cornerStrokeColor: 'blue',
    cornerStyle: 'circle',
    cornerDashArray: [2, 2],
    padding: 10,
    borderColor: 'orange',
    borderDashArray: [3, 1, 3],
    borderScaleFactor: 2,
  }
}

const setRectDefaultOptions = () => {
  fabric.Rect.ownDefaults = {
    ...fabric.Rect.ownDefaults,
    strokeUniform: true,
  }
}

const setfabricCanvas = () => {
  const width = canvasRef.value.offsetWidth
  const height = canvasRef.value.offsetHeight

  const canvas = new fabric.Canvas(canvasRef.value, {
    width,
    height,
    backgroundColor,
    backgroundImage,
  })
  canvas.requestRenderAll()
  setCanvas(markRaw(canvas))
}
/**
 * @param {fabric.Canvas} canvas
 */
const registerEvent = (canvas) => {
  canvas.on('dragenter', ({ e }) => {
    e.preventDefault()
    e.stopPropagation()
  })
  canvas.on('dragover', ({ e }) => {
    e.preventDefault()
    e.stopPropagation()
  })
  canvas.on('object:scaling', (e) => {
    console.log(e)
  })
}
const init = () => {
  setDefaultOptions()
  setRectDefaultOptions()

  setInteractiveObjectControls()
  setTextBoxControls()
  setGroupControls()
  setRectControls()
  setLineControls()

  setfabricCanvas()
  registerEvent(canvas.value)
}

onMounted(() => {
  init()
})
</script>

<style lang="scss" scoped>
.fabric-canvas-wrap {
  width: 100%;
  height: 100%;
  overflow: auto;
  scrollbar-color: #0a3c85 #07275b;
  scrollbar-width: thin;
  #fabric-canvas {
    display: block;
    width: 100%;
    height: 100%;
  }
}
</style>
